package com.hq.play.view.model;

import androidx.lifecycle.LiveData;
import androidx.lifecycle.ViewModel;
import androidx.lifecycle.ViewModelKt;
import androidx.paging.Pager;
import androidx.paging.PagingConfig;
import androidx.paging.PagingData;
import androidx.paging.PagingLiveData;

import com.google.common.util.concurrent.ListeningExecutorService;
import com.google.common.util.concurrent.MoreExecutors;
import com.hq.play.base.VideoBaseDataSourceAll;
import com.hq.play.base.data.PageData;
import com.hq.play.base.data.VideoEnityData;
import com.hq.play.util.HttpSevvice;
import com.hq.play.util.IhttpService;

import java.util.concurrent.Executors;

import kotlinx.coroutines.CoroutineScope;
import lombok.Getter;

public class PagingModel extends ViewModel {
    private final CoroutineScope coroutineScope;
    private ListeningExecutorService pool;//线程池
    private PagingConfig config;//初始化配置
    @Getter
    private LiveData<PagingData<VideoEnityData>> data;
    private IhttpService httpService;//联网服务接口
    public PagingModel() {
        // 初始化服务
        this.config=new PagingConfig(PageData.pageSize,20,false);
        this.pool= MoreExecutors.listeningDecorator(Executors.newCachedThreadPool());
        this.httpService=new HttpSevvice(this.pool);
        this.coroutineScope = ViewModelKt.getViewModelScope(this);

        VideoBaseDataSourceAll baseData=new VideoBaseDataSourceAll(this.httpService,this.pool);
        Pager<Integer, VideoEnityData> pager = new Pager<Integer,VideoEnityData>(this.config, ()->baseData);
        this.data= PagingLiveData.cachedIn(PagingLiveData.getLiveData(pager), coroutineScope);
    }

    /**
     * 刷新数据原
     */
    public final void refreshBaseData(){
        VideoBaseDataSourceAll baseData=new VideoBaseDataSourceAll(this.httpService,this.pool);
        Pager<Integer, VideoEnityData> pager = new Pager<Integer,VideoEnityData>(this.config, ()->baseData);
        this.data= PagingLiveData.cachedIn(PagingLiveData.getLiveData(pager), coroutineScope);

    }
}
